$(function(){

});

(function( $ ){

    $.fn.labelauty = function( options )
    {
        /*
         * Our default settings
         * Hope you don't need to change anything, with these settings
         */
        var settings = $.extend(
            {
                // Development Mode
                // This will activate console debug messages
                development: false,

                // Trigger Class
                // This class will be used to apply styles
                class: "labelauty",

                // Use text label ?
                // If false, then only an icon represents the input
                label: true,

                // Separator between labels' messages
                // If you use this separator for anything, choose a new one
                separator: "|",

                // Default Checked Message
                // This message will be visible when input is checked
                checked_label: "Checked",

                // Default UnChecked Message
                // This message will be visible when input is unchecked
                unchecked_label: "Unchecked",

                // Minimum Label Width
                // This value will be used to apply a minimum width to the text labels
                minimum_width: false,

                // Use the greatest width between two text labels ?
                // If this has a true value, then label width will be the greatest between labels
                same_width: true
            }, options);

        /*
         * Let's create the core function
         * It will try to cover all settings and mistakes of using
         */
        return this.each(function()
        {
            var $object = $( this );
            var use_labels = true;
            var labels;
            var labels_object;
            var input_id;

            // Test if object is a check input
            // Don't mess me up, come on
            if( $object.is( ":checkbox" ) === false && $object.is( ":radio" ) === false )
                return this;

            // Add "labelauty" class to all checkboxes
            // So you can apply some custom styles
            $object.addClass( settings.class );

            // Get the value of "data-labelauty" attribute
            // Then, we have the labels for each case (or not, as we will see)
            labels = $object.attr( "data-labelauty" );

            use_labels = settings.label;

            // It's time to check if it's going to the right way
            // Null values, more labels than expected or no labels will be handled here
            if( use_labels === true )
            {
                if( labels == null || labels.length === 0 )
                {
                    // If attribute has no label and we want to use, then use the default labels
                    labels_object = new Array();
                    labels_object[0] = settings.unchecked_label;
                    labels_object[1] = settings.checked_label;
                }
                else
                {
                    // Ok, ok, it's time to split Checked and Unchecked labels
                    // We split, by the "settings.separator" option
                    labels_object = labels.split( settings.separator );

                    // Now, let's check if exist _only_ two labels
                    // If there's more than two, then we do not use labels :(
                    // Else, do some additional tests
                    if( labels_object.length > 2 )
                    {
                        use_labels = false;
                        debug( settings.development, "There's more than two labels. LABELAUTY will not use labels." );
                    }
                    else
                    {
                        // If there's just one label (no split by "settings.separator"), it will be used for both cases
                        // Here, we have the possibility of use the same label for both cases
                        if( labels_object.length === 1 )
                            debug( settings.development, "There's just one label. LABELAUTY will use this one for both cases." );
                    }
                }
            }

            /*
             * Let's begin the beauty
             */

            // Start hiding ugly checkboxes
            // Obviously, we don't need native checkboxes :O
            $object.css({ display : "none" });

            // We don't need more data-labelauty attributes!
            // Ok, ok, it's just for beauty improvement
            $object.removeAttr( "data-labelauty" );

            // Now, grab checkbox ID Attribute for "label" tag use
            // If there's no ID Attribute, then generate a new one
            input_id = $object.attr( "id" );

            if( input_id == null )
            {
                var input_id_number = 1 + Math.floor( Math.random() * 1024000 );
                input_id = "labelauty-" + input_id_number;

                // Is there any element with this random ID ?
                // If exists, then increment until get an unused ID
                while( $( input_id ).length !== 0 )
                {
                    input_id_number++;
                    input_id = "labelauty-" + input_id_number;
                    debug( settings.development, "Holy crap, between 1024 thousand numbers, one raised a conflict. Trying again." );
                }

                $object.attr( "id", input_id );
            }

            // Now, add necessary tags to make this work
            // Here, we're going to test some control variables and act properly
            $object.after( create( input_id, labels_object, use_labels ) );

            // Now, add "min-width" to label
            // Let's say the truth, a fixed width is more beautiful than a variable width
            if( settings.minimum_width !== false )
                $object.next( "label[for=" + input_id + "]" ).css({ "min-width": settings.minimum_width });

            // Now, add "min-width" to label
            // Let's say the truth, a fixed width is more beautiful than a variable width
            if( settings.same_width != false && settings.label == true )
            {
                var label_object = $object.next( "label[for=" + input_id + "]" );
                var unchecked_width = getRealWidth(label_object.find( "span.labelauty-unchecked" ));
                var checked_width = getRealWidth(label_object.find( "span.labelauty-checked" ));

                if( unchecked_width > checked_width )
                    label_object.find( "span.labelauty-checked" ).width( unchecked_width );
                else
                    label_object.find( "span.labelauty-unchecked" ).width( checked_width );
            }
        });
    };

    /*
     * Tricky code to work with hidden elements, like tabs.
     * Note: This code is based on jquery.actual plugin.
     * https://github.com/dreamerslab/jquery.actual
     */
    function getRealWidth( element )
    {
        var width = 0;
        var $target = element;
        var style = 'position: absolute !important; top: -1000 !important; ';

        $target = $target.clone().attr('style', style).appendTo('body');
        width = $target.width(true);
        $target.remove();

        return width;
    }

    function debug( debug, message )
    {
        if( debug && window.console && window.console.log )
            window.console.log( "jQuery-LABELAUTY: " + message );
    };

    function create( input_id, messages_object, label )
    {
        var block;
        var unchecked_message;
        var checked_message;

        if( messages_object == null )
            unchecked_message = checked_message = "";
        else
        {
            unchecked_message = messages_object[0];

            // If checked message is null, then put the same text of unchecked message
            if( messages_object[1] == null )
                checked_message = unchecked_message;
            else
                checked_message = messages_object[1];
        }

        if( label == true )
        {
            block = '<label for="' + input_id + '">' +
                '<span class="labelauty-unchecked-image"></span>' +
                '<span class="labelauty-unchecked">' + unchecked_message + '</span>' +
                '<span class="labelauty-checked-image"></span>' +
                '<span class="labelauty-checked">' + checked_message + '</span>' +
                '</label>';
        }
        else
        {
            block = '<label for="' + input_id + '">' +
                '<span class="labelauty-unchecked-image"></span>' +
                '<span class="labelauty-checked-image"></span>' +
                '</label>';
        }

        return block;
    };

}( jQuery ));


function getUrlRelativePath()
{
    var url = document.location.toString();
    var arrUrl = url.split("//");
    var start = arrUrl[1].indexOf("/");
    var relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符
    if(relUrl.indexOf("?") != -1){
        relUrl = relUrl.split("?")[0];
    }
    return relUrl;
}

function getUrlPara()
{
    var url = document.location.toString();
    var arrUrl = url.split("?");
    var para = arrUrl[1];
    return para;
}



function ajaxPage(elm,link){
    $.ajax({
        url:link,
        type:"GET",
        success:function(da){
            elm.html(da);
        }
    });
}

function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return decodeURI(r[2]);
    return "";
}


$.ajaxSetup({
    error: function (XMLHttpRequest, textStatus, errorThrow) {
        var jsonMsg = JSON.parse(XMLHttpRequest.responseText);
        if (jsonMsg) {
                $.toast(jsonMsg.resultMsg);
        }
    }
});

function enableOrDisableBtn($elm,enable,btnTx){
    if(enable){
        $elm.removeClass("weui-btn_disabled");
        $elm.html(btnTx?btnTx:" 提交数据 ");
    }else{
        $elm.addClass("weui-btn_disabled");
        $elm.html("<i class=\"weui-loading\"></i> 保存中...  ");
    }

}

// FastClick.attach(document.body);
(function (jq) {
    //opt:配置
    //  name = input表单名称(默认uploadfile)
    //  exts = 允许的后缀名(array,默认4种图片格式)
    //  max = 最大上传数量(默认3)
    //  size = 文件最大大小(字节,默认3M)
    //  del = 移除图片时是否提示(默认提示)
    //msg:消息内容，配置项与opt项同
    jq.fn.h5upload = function (opt, msg) {
        opt = jq.extend({ exts: ['jpg', 'gif', 'png', 'jpeg'], max: 1, size: 10145728, del: true, name: 'uploadfile' }, opt);
        msg = jq.extend({ exts: "文件格式不合法！", max: "最多允许上传" + opt.max + "张", size: "文件大小不得超过" + (opt.size / 1024) + "kb", del: "是否移除此图像？" }, msg);
        var $self = $(this);
        var $plus = null;
        var curFileCount = 0;
        function onadd() {
           // $self.find("input[name=" + opt.name+ "]:last").click();
            return $self.find("input[name=" + opt.name+ "]:last").trigger("click");
        }
        function addEvent($input) {
            $input.change(function () {
                var file = this.files[0];
                if (checkFile(file)) {
                    var r = new FileReader();
                    r.readAsDataURL(file);
                    r.onload = function () {
                        lrz(file, {width: 750})
                            .then(function (results) {
                                if(opt.cut){
                                    $.toast('请按示例进行裁剪', 'text');
                                    // 你需要的数据都在这里，可以以字符串的形式传送base64给服务端转存为图片。
                                    /* console.log(results);
                                     console.log(results.blob);
                                     console.log(results.origin.size);
                                     console.log(results.base64);
                                     console.log(results.base64.length * 0.8);*/


                                    $img = $("<div class='cropper-body'><img class='cropper-image' src='" + results.base64 + "'></div>");
                                    $('.cropper-preview').append($img);
                                    $(".weui-gallery").show();

                                    //cropper
                                    var $image = $('.cropper-image');
                                    var $button = $('.btn-cropper');
                                    var croppable = false;
                                    $image.cropper({
                                        aspectRatio: 1,
                                        viewMode: 1,
                                        dragMode: 'move', // 'crop', 'move' or 'none'
                                        cropBoxMovable: false,
                                        cropBoxResizable: false,
                                        built: function () {
                                            croppable = true;
                                        }
                                    });
                                    $button.unbind("click").on('click', function () {
                                        $.toast('处理中，请稍候', 'text');
                                        var croppedCanvas = null;
                                        if (!croppable) {
                                            return;
                                        }
                                        // Crop
                                        croppedCanvas = $image.cropper('getCroppedCanvas');
                                        $imgdiv = $("<div class='h5upload_item h5upload_img' style='background-image:url(" + croppedCanvas.toDataURL() + ")'></div>");
                                        $imgclose = $("<img class='h5upload_delimg' src='" + closeimg + "'/>");
                                        //保存关联对象到dom，以便删除使用
                                        $imgclose[0].link = [$input, $imgdiv];
                                        $imgclose.unbind("click").on('click', function () {
                                            removefile(this);
                                            $self.find("input[name=" + opt.name + "]:last").data('base64', '');
                                        });
                                        $image.cropper("reset");
                                        $('#cutContainer').find('.cropper-preview').empty();
                                        $(".weui-gallery").hide();
                                        setTimeout(function () {
                                            $plus.before($imgdiv.append($imgclose));
                                            $self.find("input[name=" + opt.name + "]:last").data('base64', croppedCanvas.toDataURL());
                                            newfile();
                                        }, 1000);

                                    });
                                }else{
                                    if(opt.restric==true)
                                        $imgdiv = $("<div class='h5upload_item h5upload_img' style='background-image:url(" + results.base64 + ")'></div>");
                                    else
                                        $imgdiv = $("<div  class='h5upload_img' style='width:80%;display: inline-block'><img src='"+results.base64+"' style='border-radius: 3%;width:100%'></div>");
                                    $imgclose = $("<img class='h5upload_delimg' src='" + closeimg + "'/>");
                                    //保存关联对象到dom，以便删除使用
                                    $imgclose[0].link = [$input, $imgdiv];
                                    $imgclose.unbind("click").on('click', function () {
                                        removefile(this);
                                        $self.find("input[name=" + opt.name + "]:last").data('base64', '');
                                    });
                                    $.toast('处理中，请稍候', 'text');
                                    setTimeout(function(){
                                        if(opt.restric==true)
                                            $plus.before($imgdiv.append($imgclose));
                                        else
                                            $self.prepend($imgdiv.append($imgclose));
                                        $self.find("input[name=" + opt.name+ "]:last").data('base64', results.base64);
                                        newfile();
                                    },2000);
                                }

                            })
                                .catch(function (err) {
                                    // 处理失败会执行
                                    console.log(err)
                                    $.toast('图片加载失败，请重试！:' + err);
                                    setTimeout(function () {
                                    }, 1000);
                                })
                                .always(function () {});

                        }
                }
            });
        }
        function addInput($parent) {
            return $("<input type='file' name='" + opt.name + "' style='display:none'/>").appendTo($parent);
        }
        function newfile() {
            if (curFileCount < opt.max) {
                $input = addInput($self);
                addEvent($input);
                curFileCount++;
            }else{
                $plus.hide();
            }
            return true;
        }
        function removefile(base) {
            if (opt.del) {
                $.confirm(msg.del, function () {
                    if(curFileCount!=1){
                        base.link[0].remove();
                        curFileCount--;
                    }
                    base.link[1].remove();
                    if (curFileCount <= opt.max) {
                        $plus.show();
                    }
                });
            }
        }
        function init() {
            if(opt.cut)
                $plus = $("<img src='"+plusimg+"' class='h5upload_item'/>");
            else
                $plus = $("<img src='"+plusimg+"' class='h5upload_item' style='float:unset'/>");
            $self.append($plus).append("<div class='h5upload_clear'></div>");
            $plus.mouseup(onadd);
            return $plus;
        }
        function checkFile(file) {
            //后缀名检测
            var sps = file.name.substring(file.name.lastIndexOf(".")+1,file.name.length);
            if (opt.exts.indexOf(sps.toLowerCase()) < 0) return falsemsg('exts');
            //大小检测
            if (file.size > opt.size) return falsemsg("size");
            return true;
        }
        function falsemsg(key) {
            //if (msg[key]) alert(msg[key]);
            if (msg[key]) $.alert(msg[key]);
            return false;
        }
        $plus = init();
        newfile();
    }
    var plusimg = "";
    var closeimg = "";
    var style = ".h5upload_item{float:left;width:70px;height:70px;margin:5px}.h5upload_clear{clear:both}.h5upload_img{background-size:cover;position:relative}.h5upload_delimg{position:absolute;top:-5px;right:-5px;width:18px;height:18px}";
    //输出style到页面
    document.write("<style>"+style+"</style>")
})(jQuery);

(function (jq) {
    //opt:配置
    //  name = input表单名称(默认uploadfile)
    //  exts = 允许的后缀名(array,默认4种图片格式)
    //  max = 最大上传数量(默认3)
    //  size = 文件最大大小(字节,默认3M)
    //  del = 移除图片时是否提示(默认提示)
    //msg:消息内容，配置项与opt项同
    jq.fn.h5uploadSilence = function (opt, msg) {
        opt = jq.extend({ exts: ['jpg', 'gif', 'png', 'jpeg'], max: 1, size: 10145728, del: true, name: 'uploadfile',callback:function(){} }, opt);
        msg = jq.extend({ exts: "文件格式不合法！", max: "最多允许上传" + opt.max + "张", size: "文件大小不得超过" + (opt.size / 1024) + "kb", del: "是否移除此图像？" }, msg);
        var $self = $(this);
        function addEvent($input) {
            $input.change(function () {
                var file = this.files[0];
                if (checkFile(file)) {
                    var r = new FileReader();
                    r.readAsDataURL(file);
                    r.onload = function () {
                        lrz(file, {width: 750})
                            .then(function (results) {
                                        $("body").find("input[name=" + opt.name+ "]:last").data('base64', results.base64);
                                        opt.callback(results.base64);
                            })
                            .catch(function (err) {
                                // 处理失败会执行
                                console.log(err)
                                $.toast('图片加载失败，请重试！:' + err);
                                setTimeout(function () {
                                }, 1000);
                            })
                            .always(function () {});

                    }
                }
            });
        }
        function init() {
            $("body").append("<input type='file' name='" + opt.name + "' style='display:none'/>");
            $self.click(function (){
                $("input[name=" + opt.name+ "]:last").trigger("click");
                return false;
            });
            addEvent($("body").find("input[name=" + opt.name+ "]:last"));
        }
        function checkFile(file) {
            //后缀名检测
            var sps = file.name.substring(file.name.lastIndexOf(".")+1,file.name.length);
            if (opt.exts.indexOf(sps.toLowerCase()) < 0) return falsemsg('exts');
            //大小检测
            if (file.size > opt.size) return falsemsg("size");
            return true;
        }
        function falsemsg(key) {
            //if (msg[key]) alert(msg[key]);
            if (msg[key]) $.alert(msg[key]);
            return false;
        }
        init();
    }
})(jQuery);

var serverAdd="http://doctor.kriss.top";
var appId ="wxfdf0bff47699990a";
var qiniuChatImgDomain="http://p9v0cz6eo.bkt.clouddn.com";


function unkownuser(type) {
    if("doctor"==type)
        $.toast("未识别出当前医生！");
    else if("patient"==type)
        $.toast("未识别出当前患者！");
}


function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    var f = Math.round(x*100)/100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
        rs = s.length;
        s += '.';
    }
    while (s.length <= rs + 2) {
        s += '0';
    }
    return s;
}

function kksubStr(str,len){
    if(str){
        if(str.length >len)
            str = str.substring(0,len)+".."
    }
    return str;
}